﻿using System.IO;
using UnityEditor.Callbacks;
using UnityEditor;
using System;
using UnityEngine;
using System.Linq;
using System.Collections.Generic;

#if UNITY_IOS
using UnityEditor.iOS.Xcode;
#endif

namespace Balaso
{
    /// <summary>
    /// PostProcessor script to automatically fill all required dependencies
    /// for App Tracking Transparency
    /// </summary>
    public class AppTrackingTransparencyPostProcessor
    {
#if UNITY_IOS
        [PostProcessBuild]
        public static void OnPostprocessBuild(BuildTarget buildTarget, string buildPath)
        {
            if (buildTarget == BuildTarget.iOS)
            {
                

                /*
                 * PBXProject
                 */
                PBXProject project = new PBXProject();
                string projectPath = PBXProject.GetPBXProjectPath(buildPath);
                project.ReadFromFile(projectPath);

                // If loaded, add `AppTrackingTransparency` Framework
                if (project != null)
                {
                    string targetId;

    #if UNITY_2019_3_OR_NEWER
                    targetId = project.GetUnityFrameworkTargetGuid();
#else
                    targetId = project.TargetGuidByName("Unity-iPhone");
#endif

                    
                   // project.SetBuildProperty(project.GetUnityMainTargetGuid(), "ENABLE_BITCODE", "NO");


                    project.AddFrameworkToProject(targetId, "AppTrackingTransparency.framework", true);
                    project.AddFrameworkToProject(targetId, "AdSupport.framework", false);
                    project.AddFrameworkToProject(targetId, "StoreKit.framework", false);


                    project.AddFrameworkToProject(targetId, "libz.dylib", false);
                    project.AddFrameworkToProject(targetId, "libsqlite3.tbd", false);
                    project.AddFrameworkToProject(targetId, "CoreTelephony.framework", false);

                    //bitcode修改（所有名称在Xcode中可见）
                    project.SetBuildProperty(targetId, "ENABLE_BITCODE", "NO");
                   
                    project.SetBuildProperty(targetId, "GCC_ENABLE_OBJC_EXCEPTIONS", "YES");

                    project.SetBuildProperty(targetId, "GCC_C_LANGUAGE_STANDARD", "gnu99");

                    project.AddBuildProperty(targetId, "OTHER_LDFLAGS", "-ObjC");
                    project.AddBuildProperty(targetId, "OTHER_LDFLAGS", "-fobjc-arc");
                    project.AddFileToBuild(targetId, project.AddFile("usr/lib/libxml2.tbd", "Libraries/libxml2.tbd", PBXSourceTree.Sdk));
                    project.AddFileToBuild(targetId, project.AddFile("usr/lib/libresolv.9.tbd", "Libraries/libresolv.9.tbd", PBXSourceTree.Sdk));
#if UNITY_2019_3_OR_NEWER
                //    project.AddFileToBuild(targetId, project.AddFile("Frameworks/AnyThinkAds/Plugins/iOS/Core/AnyThinkSDK.bundle", "Frameworks/AnyThinkAds/Plugins/iOS/Core/AnyThinkSDK.bundle", PBXSourceTree.Sdk));
#else
#endif


                    project.WriteToFile(PBXProject.GetPBXProjectPath(buildPath));
                }

                /*
                 * PList
                 */
                PlistDocument plist = new PlistDocument();
                plist.ReadFromString(File.ReadAllText(buildPath + "/Info.plist"));
                if (plist != null)
                {
                    // Get root
                    PlistElementDict rootDict = plist.root;

                    string[] LSApplicationQueriesSchemesValueList = { "openapp.jdmobile","vipshop","tbopen","tmall","suning","ctrip","qunariphone","imeituan","dianping","lianjia","pddopen","xhsdiscover","baiduhaokan","bdminivideo","baiduboxlite","baiduboxmission","com.baidu.tieba","zhihu","wireless1688","iqiyi","weixin","qihooloan","weishi","travelguide","wbmain","taobaotravel","kwai","ksnebula","sinaweibo","alipays","youku","openjdlite","com.360buy.jdpingou","cainiao","kaola","OneTravel","lianjiabeike","iosamap" };
                    PlistElementArray LSApplicationQueriesSchemesArray = plist.root.CreateArray("LSApplicationQueriesSchemes");
                    for (int i = 0; i < LSApplicationQueriesSchemesValueList.Length; i++)
                    {
                        LSApplicationQueriesSchemesArray.AddString(LSApplicationQueriesSchemesValueList[i]);


                    }// Add NSUserTrackingUsageDescription
                        rootDict.SetString("NSUserTrackingUsageDescription", SettingsInspector.Settings.PopupMessage);

                    // Check if SKAdNetworkItems already exists
                    PlistElementArray SKAdNetworkItems = null;
                    if (rootDict.values.ContainsKey("SKAdNetworkItems"))
                    {
                        try
                        {
                            SKAdNetworkItems = rootDict.values["SKAdNetworkItems"] as PlistElementArray;
                        }
                        catch (Exception e)
                        {
                            Debug.LogWarning(string.Format("Could not obtain SKAdNetworkItems PlistElementArray: {0}", e.Message));
                        }
                    }

                    // If not exists, create it
                    if (SKAdNetworkItems == null)
                    {
                        SKAdNetworkItems = rootDict.CreateArray("SKAdNetworkItems");
                    }

                    if (SettingsInspector.Settings.SkAdNetworkIds != null)
                    {
                        List<string> networkIdsWithoutDuplicates = SettingsInspector.Settings.SkAdNetworkIds.Distinct().ToList();
                        string plistContent = File.ReadAllText(buildPath + "/Info.plist");
                        for (int i = 0; i < networkIdsWithoutDuplicates.Count; i++)
                        {
                            if (!plistContent.Contains(networkIdsWithoutDuplicates[i]))
                            {
                                PlistElementDict SKAdNetworkIdentifierDict = SKAdNetworkItems.AddDict();
                                SKAdNetworkIdentifierDict.SetString("SKAdNetworkIdentifier", networkIdsWithoutDuplicates[i]);
                            }
                        }
                    }

                    File.WriteAllText(buildPath + "/Info.plist", plist.WriteToString());
                }
            }
        }
#endif
    }
}